package com.tarena.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author WangPeihu
 * @since 31/12/2009
 * @Team [Never give up]
 * 
 *       1. emp_list :显示所有员工 <br>
 *       2. emp_add_form :添加员工的表单界面<br>
 *       4. emp_delete :删除一个员工<br>
 *       5. emp_update_form :更新一个员工请求地址<br>
 *       6. emp_update_detail:更新一个员工的表单界面<br>
 *       7. login_form :登录表单界面<br>
 *       8. login :登录请求<br>
 */
@SuppressWarnings("serial")
public class ActionServlet extends HttpServlet {

	private static final String prefix = "/emp/";

	private Properties config = new Properties();

	/**
	 * @加在配置文件信息，该方法在本应用启动的第一次加载，以后就不加在了
	 */
	public void init() throws ServletException {
		try {
			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream(
							"com/tarena/controller/config.properties");
			config.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @用于处理客户端发来的各种请求，并返回
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/** 得到不包括请求参数字符串的URL */
		String url = request.getRequestURI();
		String path = url.substring(url.indexOf(prefix) + prefix.length());
		try {
			String className = config.getProperty(path);
			String ctx = request.getContextPath();
			System.out.println("This program :" + ctx);
			/** Create new Object */
			Class clazz = Class.forName(className);
			Action action = (Action) clazz.newInstance();

			/** call this object's execute method */
			action.execute(request, response);
		} catch (Exception e) {
			throw new ServletException(e);
		}

	}
}
